const daoModule = require('./Dao')
const database = require('../modules/databse')

// 获取权限列表
module.exports.list = function (cb) {
    const db = database.getDataBase()
    const sql = "SELECT * FROM sp_permission_api as api LEFT JOIN sp_permission as main ON main.ps_id = api.ps_id WHERE main.ps_id is not null"
    db.driver.execQuery(sql, function(err, result) {
        if (err) return cb('获取权限列表失败', null)
        cb(null, result)
    })
}

// 权限验证
module.exports.authRight = function (rid, serviceName, actionName, cb) {
    // 角色ID为超级管理员
    if (rid == 0) return cb(null, true)

    // 权限验证
    daoModule.findOne('PermissionAPIModel', {
        "ps_api_service": serviceName,
        "ps_api_action": actionName
    }, function (err, permissionAPI) {
        if (err || !permissionAPI) return cb('无权限访问', false)

        daoModule.findOne('RoleModel', { "role_id": rid}, function (err, role) {
            if (err || !role) return cb('获取角色信息失败', false)
            const ps_ids = role.ps_ids.split(',')
            for (idx in ps_ids) {
                const ps_id = ps_ids[idx]
                if (parseInt(permissionAPI.ps_id) == parseInt(ps_id)) {
                    return cb(null, true)
                }
            }
            return cb('无权限访问', false)
        })
    })
}